package aad.storyboard.controller;

import java.util.Observable;
import java.util.Observer;

import aad.storyboard.model.AnimationProvider;
import android.util.Log;
import android.view.View;

public class FrameRateController extends Observable implements Runnable{
	
	

	private int fps = 27;
	private View mainLayout;
	private boolean active = true;
	private boolean stop = false;
	
	private static FrameRateController instance = new FrameRateController();
	
	
	public static FrameRateController getInstance(View layout){
		instance.setMainLayout(layout);
		return instance;
	}
	
	public static void unsubscribeObserver(Observer observer){
		instance.deleteObserver(observer);
	}
	
	private FrameRateController(){}
	
	/**
	 * main thread. if it is active and the view exists (the application is running), it triggers the observers (animations) and invalidates the view after that
	 */
	public void run(){
		
		while(this.mainLayout == null){
			Log.e("TAG","mainlayout null");
			try {
				Thread.sleep(1000/this.fps);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//this.mainLayout = ControllerManager.getInstance().getGuiComposer().getMainView();
			if(this.stop)
				return;
		}
		
		int c = 0;
		
		while(true){
			try {
				Thread.sleep(1000/this.fps);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(this.active ){
			this.setChanged();
			this.notifyObservers();}
			mainLayout.postInvalidate();
			if(this.stop)
				return;
		}
		
	}

	//getters and setters
	public int getFps() {
		return fps;
	}

	public void setFps(int fps) {
		this.fps = fps;
	}
	
	public void setMainLayout(View v){
		this.mainLayout = v;
	}

	public void setActive(boolean b) {
		this.active = b;
	}

	public void stop() {
		this.stop  = true;
		
	}
	
}
